import { isConstructor, Token } from "../utils";

type InjectIonParams = {
  attr: string;
} & (
  | {
      target: Constructor;
    }
  | {
      ref: () => Constructor;
    }
);

//对注入类的二次封装
export default class Injection {
  constructor(private params: InjectIonParams) {}

  //获取注入key
  get key() {
    return this.params.attr;
  }

  //工厂函数 判断注入是否为类后存入Injection实例
  factory() {

    let constructor: Constructor;
    if ("ref" in this.params) {
      constructor = this.params.ref();
    } else {
      constructor = this.params.target;
    }

    if (isConstructor(constructor)) {
      return new constructor();
    } else {
      throw new Error("请将类注入进@inject====> " + this.params.attr);
    }
  }

  //获取由注入类创建的Token
  getToken() {
    if ("ref" in this.params) {
      return Token.create(this.params.ref());
    }
    return Token.create(this.params.target);
  }
}
